package com.ghsc.ghxc.jsb.ui.live.view.cust

import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ActivityUtils
import com.cn.appcore.ext.*
import com.cn.appcore.utils.GlideEngine
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.databinding.ImCustRichTextViewBinding
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.netease.yunxin.kit.chatkit.ui.databinding.ChatBaseMessageViewHolderBinding
import com.netease.yunxin.kit.chatkit.ui.model.ChatMessageBean
import com.netease.yunxin.kit.chatkit.ui.normal.view.message.viewholder.NormalChatBaseMessageViewHolder
import com.netease.yunxin.kit.common.ui.utils.TimeFormatUtils

/**
 * 项目：GuoHuaMall
 * 包名：com.ghsc.ghxc.ui.message.yunxin.view
 * 类名：CusRedAttachmentViewHolder
 * 创建时间：2023/10/24 21:10
 * 创建人 @author： xiaolin
 * 描述 ：Todo...自定义消息。富文本
 */
class CusRichTextAttachmentViewHolder(parent: ChatBaseMessageViewHolderBinding, viewType: Int) : NormalChatBaseMessageViewHolder(
    parent, viewType
) {

    private var binding //创建自己的layout布局
            : ImCustRichTextViewBinding? = null
    override fun addViewToMessageContainer() {
        binding = ImCustRichTextViewBinding.inflate(
            LayoutInflater.from(parent.context), messageContainer, true
        )
    }

    //去掉背景
    override fun onMessageBackgroundConfig(messageBean: ChatMessageBean?) {
        baseViewBinding.messageContainer.setBackgroundResource(R.color.title_transfer)
    }



    override fun bindData(message: ChatMessageBean?, lastMessage: ChatMessageBean?) {
        super.bindData(message, lastMessage)
        currentMessage = message
        val bean = message!!.messageData.message.attachment as CusRichTextAttachment
            ?: return

        binding?.let {
//            val para1 = it.llItem.layoutParams
//            para1.width =
//                StringUtil.dp2px((StringUtil.screenWidth() / StringUtil.screenDensity())-16).toInt()
//            it.llItem.layoutParams = para1
            //==1 是右边
//            val time =
//                RongDateUtils.getConversationFormatDate(uiMessage.sentTime, holder.context)
//            it.setText(R.id.top_title,message?.title)
//                .setText(R.id.crt_time,time)
            // 获取待展示消息时间戳，若为 0 则设置为当前系统时间
            val createTime =
                if (message.messageData.message.time == 0L) System.currentTimeMillis() else message.messageData.message.time
            it.crtTime.text =
                TimeFormatUtils.formatMillisecond(parent.context, createTime)
            it.topTitle.text=bean.title
            if (!TextUtils.isEmpty(bean.contentX)) {
                it.webView.visibility=View.VISIBLE
                val webSettings: WebSettings = it.webView.settings
                webSettings.javaScriptEnabled = true //允许使用js
                //设置WebView是否支持使用屏幕控件或手势进行缩放，默认是true，支持缩放
                webSettings.setSupportZoom(false)
                //设置WebView是否使用其内置的变焦机制，该机制集合屏幕缩放控件使用，默认是false，不使用内置变焦机制
                webSettings.builtInZoomControls = false
                //置WebView使用内置缩放机制时，是否展现在屏幕缩放控件上，默认true，展现在控件上
                webSettings.displayZoomControls = false
                it.webView.addJavascriptInterface(AndroidInterface(),"android")
                it.webView.loadData(bean.contentX, "text/html", "UTF-8")
            }else{
                it.webView.visibility=View.GONE
            }

            if (!TextUtils.isEmpty(bean.jump_url)){
                it.llVersion.visibility=View.VISIBLE
                it.llItem.setSingleClickListener {
                    //跳转外部浏览器
                    if (!TextUtils.isEmpty(bean.jump_url)){
                        val uri: Uri = Uri.parse(bean.jump_url)
                        val intent = Intent(Intent.ACTION_VIEW, uri)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        parent.context.startActivity(intent)
                    }else loge("apk地址为空错误")
                }
            } else it.llVersion.visibility=View.GONE



        }
    }
    //这里是和webveiw做交互的
    inner class AndroidInterface {
        @JavascriptInterface
        fun zoomImage(urls:String,index:Int) {
            // 处理图片放大的逻辑
            var selectList: MutableList<LocalMedia> = ArrayList()
            selectList.clear()
            val activity = ActivityUtils.getTopActivity() as AppCompatActivity
            val imageUrls: List<String> = urls.split(",")
            for( i in imageUrls.indices){
                val localMedia = LocalMedia()
                localMedia.path = imageUrls[i]
                localMedia.mimeType= PictureMimeType.MIME_TYPE_IMAGE
                selectList.add(localMedia)
            }
            // 预览图片 可自定长按保存路径
            PictureSelector.create(activity)
                .themeStyle(R.style.picture_default_style) // xml设置主题
                //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) // 设置相册Activity方向，不设置默认使用系统
                .isNotPreviewDownload(true) // 预览图片长按是否可以下载
                //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定义播放回调控制，用户可以使用自己的视频播放界面
                .imageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .openExternalPreview(index, selectList)

        }

    }

}